import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'

export const useThemeStore = defineStore('theme', () => {
  // 状态
  const currentTheme = ref('light')
  const primaryColor = ref('#409EFF')
  const fontSize = ref('14px')
  const borderRadius = ref('4px')
  const animation = ref(true)
  const compactMode = ref(false)
  
  // 预设主题
  const themes = ref({
    light: {
      name: '明亮主题',
      primary: '#409EFF',
      success: '#67C23A',
      warning: '#E6A23C',
      danger: '#F56C6C',
      info: '#909399',
      background: '#ffffff',
      surface: '#f5f7fa',
      text: '#303133',
      textSecondary: '#606266',
      textPlaceholder: '#C0C4CC',
      border: '#DCDFE6',
      borderLight: '#E4E7ED',
      borderLighter: '#EBEEF5',
      borderExtraLight: '#F2F6FC'
    },
    dark: {
      name: '深色主题',
      primary: '#409EFF',
      success: '#67C23A',
      warning: '#E6A23C',
      danger: '#F56C6C',
      info: '#909399',
      background: '#1a1a1a',
      surface: '#2d2d2d',
      text: '#E5EAF3',
      textSecondary: '#CFD3DC',
      textPlaceholder: '#8D9095',
      border: '#4C4D4F',
      borderLight: '#414243',
      borderLighter: '#363637',
      borderExtraLight: '#2B2B2C'
    },
    blue: {
      name: '蓝色主题',
      primary: '#1890ff',
      success: '#52c41a',
      warning: '#faad14',
      danger: '#ff4d4f',
      info: '#d9d9d9',
      background: '#f0f2f5',
      surface: '#ffffff',
      text: '#000000d9',
      textSecondary: '#00000073',
      textPlaceholder: '#00000040',
      border: '#d9d9d9',
      borderLight: '#e8e8e8',
      borderLighter: '#f0f0f0',
      borderExtraLight: '#fafafa'
    },
    green: {
      name: '绿色主题',
      primary: '#52c41a',
      success: '#52c41a',
      warning: '#faad14',
      danger: '#ff4d4f',
      info: '#d9d9d9',
      background: '#f6ffed',
      surface: '#ffffff',
      text: '#000000d9',
      textSecondary: '#00000073',
      textPlaceholder: '#00000040',
      border: '#d9d9d9',
      borderLight: '#e8e8e8',
      borderLighter: '#f0f0f0',
      borderExtraLight: '#fafafa'
    },
    purple: {
      name: '紫色主题',
      primary: '#722ed1',
      success: '#52c41a',
      warning: '#faad14',
      danger: '#ff4d4f',
      info: '#d9d9d9',
      background: '#f9f0ff',
      surface: '#ffffff',
      text: '#000000d9',
      textSecondary: '#00000073',
      textPlaceholder: '#00000040',
      border: '#d9d9d9',
      borderLight: '#e8e8e8',
      borderLighter: '#f0f0f0',
      borderExtraLight: '#fafafa'
    }
  })

  // 计算属性
  const isDark = computed(() => currentTheme.value === 'dark')
  const currentThemeConfig = computed(() => themes.value[currentTheme.value] || themes.value.light)
  
  const cssVariables = computed(() => {
    const theme = currentThemeConfig.value
    return {
      '--el-color-primary': theme.primary,
      '--el-color-success': theme.success,
      '--el-color-warning': theme.warning,
      '--el-color-danger': theme.danger,
      '--el-color-info': theme.info,
      '--el-bg-color': theme.background,
      '--el-bg-color-page': theme.surface,
      '--el-text-color-primary': theme.text,
      '--el-text-color-regular': theme.textSecondary,
      '--el-text-color-placeholder': theme.textPlaceholder,
      '--el-border-color': theme.border,
      '--el-border-color-light': theme.borderLight,
      '--el-border-color-lighter': theme.borderLighter,
      '--el-border-color-extra-light': theme.borderExtraLight,
      '--el-font-size-base': fontSize.value,
      '--el-border-radius-base': borderRadius.value
    }
  })

  // 方法
  const setTheme = (themeName) => {
    if (themes.value[themeName]) {
      currentTheme.value = themeName
      applyTheme()
      saveThemeToStorage()
    }
  }

  const setPrimaryColor = (color) => {
    primaryColor.value = color
    // 更新当前主题的主色
    if (themes.value[currentTheme.value]) {
      themes.value[currentTheme.value].primary = color
    }
    applyTheme()
    saveThemeToStorage()
  }

  const setFontSize = (size) => {
    fontSize.value = size
    applyTheme()
    saveThemeToStorage()
  }

  const setBorderRadius = (radius) => {
    borderRadius.value = radius
    applyTheme()
    saveThemeToStorage()
  }

  const toggleAnimation = () => {
    animation.value = !animation.value
    applyTheme()
    saveThemeToStorage()
  }

  const toggleCompactMode = () => {
    compactMode.value = !compactMode.value
    applyTheme()
    saveThemeToStorage()
  }

  const applyTheme = () => {
    const root = document.documentElement
    
    // 应用CSS变量
    Object.entries(cssVariables.value).forEach(([key, value]) => {
      root.style.setProperty(key, value)
    })
    
    // 设置主题类名
    root.className = `theme-${currentTheme.value}`
    
    // 设置动画
    if (!animation.value) {
      root.classList.add('no-animation')
    } else {
      root.classList.remove('no-animation')
    }
    
    // 设置紧凑模式
    if (compactMode.value) {
      root.classList.add('compact-mode')
    } else {
      root.classList.remove('compact-mode')
    }
    
    // 设置meta主题色
    const metaThemeColor = document.querySelector('meta[name="theme-color"]')
    if (metaThemeColor) {
      metaThemeColor.setAttribute('content', currentThemeConfig.value.primary)
    }
  }

  const saveThemeToStorage = () => {
    const themeData = {
      currentTheme: currentTheme.value,
      primaryColor: primaryColor.value,
      fontSize: fontSize.value,
      borderRadius: borderRadius.value,
      animation: animation.value,
      compactMode: compactMode.value
    }
    localStorage.setItem('themeConfig', JSON.stringify(themeData))
  }

  const loadThemeFromStorage = () => {
    try {
      const saved = localStorage.getItem('themeConfig')
      if (saved) {
        const themeData = JSON.parse(saved)
        currentTheme.value = themeData.currentTheme || 'light'
        primaryColor.value = themeData.primaryColor || '#409EFF'
        fontSize.value = themeData.fontSize || '14px'
        borderRadius.value = themeData.borderRadius || '4px'
        animation.value = themeData.animation !== false
        compactMode.value = themeData.compactMode || false
      }
    } catch (error) {
      console.error('加载主题配置失败:', error)
    }
  }

  const resetTheme = () => {
    currentTheme.value = 'light'
    primaryColor.value = '#409EFF'
    fontSize.value = '14px'
    borderRadius.value = '4px'
    animation.value = true
    compactMode.value = false
    applyTheme()
    saveThemeToStorage()
  }

  const addCustomTheme = (name, config) => {
    themes.value[name] = {
      name: config.name || name,
      ...config
    }
    saveThemeToStorage()
  }

  const removeCustomTheme = (name) => {
    if (themes.value[name] && !['light', 'dark', 'blue', 'green', 'purple'].includes(name)) {
      delete themes.value[name]
      if (currentTheme.value === name) {
        setTheme('light')
      }
      saveThemeToStorage()
    }
  }

  const exportTheme = () => {
    return {
      currentTheme: currentTheme.value,
      primaryColor: primaryColor.value,
      fontSize: fontSize.value,
      borderRadius: borderRadius.value,
      animation: animation.value,
      compactMode: compactMode.value,
      customThemes: Object.fromEntries(
        Object.entries(themes.value).filter(([key]) => 
          !['light', 'dark', 'blue', 'green', 'purple'].includes(key)
        )
      )
    }
  }

  const importTheme = (themeData) => {
    try {
      if (themeData.currentTheme) currentTheme.value = themeData.currentTheme
      if (themeData.primaryColor) primaryColor.value = themeData.primaryColor
      if (themeData.fontSize) fontSize.value = themeData.fontSize
      if (themeData.borderRadius) borderRadius.value = themeData.borderRadius
      if (themeData.animation !== undefined) animation.value = themeData.animation
      if (themeData.compactMode !== undefined) compactMode.value = themeData.compactMode
      
      if (themeData.customThemes) {
        Object.assign(themes.value, themeData.customThemes)
      }
      
      applyTheme()
      saveThemeToStorage()
      return true
    } catch (error) {
      console.error('导入主题失败:', error)
      return false
    }
  }

  const initTheme = async () => {
    try {
      // 从本地存储加载主题
      loadThemeFromStorage()
      
      // 检测系统主题偏好
      if (currentTheme.value === 'auto') {
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
        currentTheme.value = prefersDark ? 'dark' : 'light'
      }
      
      // 应用主题
      applyTheme()
      
      // 监听系统主题变化
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      mediaQuery.addEventListener('change', (e) => {
        if (currentTheme.value === 'auto') {
          currentTheme.value = e.matches ? 'dark' : 'light'
          applyTheme()
        }
      })
      
      console.log('主题初始化完成')
    } catch (error) {
      console.error('主题初始化失败:', error)
      throw error
    }
  }

  // 监听主题变化
  watch(currentTheme, () => {
    applyTheme()
  })

  return {
    // 状态
    currentTheme,
    primaryColor,
    fontSize,
    borderRadius,
    animation,
    compactMode,
    themes,
    
    // 计算属性
    isDark,
    currentThemeConfig,
    cssVariables,
    
    // 方法
    setTheme,
    setPrimaryColor,
    setFontSize,
    setBorderRadius,
    toggleAnimation,
    toggleCompactMode,
    resetTheme,
    addCustomTheme,
    removeCustomTheme,
    exportTheme,
    importTheme,
    initTheme
  }
})
